package com.acme.dao.security.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.acme.controller.HomeController;
import com.acme.dao.security.DBUserDAO;
import com.acme.entity.User;
import com.acme.entity.security.DBAuthority;


@Service
@Transactional
public class DBUserDAOImpl implements DBUserDAO
{
	@Autowired
	private SessionFactory sessionFactory;
	

	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

	@Override
	public List<User> getAllUsers() 
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public User getUserByID(int userID) 
	{
		return null; //(User) sessionFactory.getCurrentSession().get(User.class, userID);
	}

	@Override
	public List<DBAuthority> getPermissionsByUser(User user) 
	{
		String querystring = "from DBAuthority where userid = :u";
		Query query = sessionFactory.getCurrentSession().createQuery(querystring);
		query.setParameter("u", user.getUserID());
		List<?> l = query.list();
		List<DBAuthority> authList = new ArrayList<DBAuthority>();
		for (Object o : l)
		{	
			DBAuthority auth = (DBAuthority) o;
			logger.info(auth.getAuthority());
			authList.add(auth);
		}
		return authList;
	}

	@Override
	public User getUserByUsername(String username)
		{
		String querystring = "from User where username = :u";
		Query query = sessionFactory.getCurrentSession().createQuery(querystring);
		query.setParameter("u", username);
		List<?> l = query.list();
		if(l.size() == 0) return null;
		else return (User) l.get(0);
		}

	@Override
	public void addAuthority(DBAuthority authority) 
	{
		sessionFactory.getCurrentSession().merge(authority);		
	}
	
	public void removeAuthority(int authID)
	{
		String querystring = "from DBAuthority where id = :i";
		Query query = sessionFactory.getCurrentSession().createQuery(querystring);
		query.setParameter("i", authID);
		List<?> l = query.list();
		if(l.size() != 0) sessionFactory.getCurrentSession().delete((DBAuthority) l.get(0));
	}
}
